<template>
  <lay-card width="1200" style="height: 800px">
    <lay-row space="20">
    <lay-col md="24">
    <lay-quote size="sm">
      <h1 slot="title">限额管理用例生成</h1>
      <!-- ✅ 添加帮助链接 -->
      <a href="https://iknow.hs.net/console/teamManage/knowledgeBase/353/docManage/library/1336/document/136889" target="_blank" style="float: right; font-size: 14px; color: #3c9cff; text-decoration: underline;">帮助文档</a>
    </lay-quote>
   </lay-col>
    </lay-row>
    <lay-row space="20">
      <lay-col md="1"></lay-col>
      <lay-col md="18">
        <lay-form :model="formData" ref="layFormRef" :rules="rules" required>
          <lay-form-item label="选择用例文件" prop="file">
            <input type="file" id="file" class="file-input" @change="handleFileChange" />
          </lay-form-item>
          <lay-form-item label="大模型类型" prop="model" >
            <lay-select v-model="formData.model" placeholder="请选择大模型类型" allow-clear>
              <lay-select-option value="Qwen2-72B-Instruct" label="千问（Qwen2-72B-Instruct）"></lay-select-option>
              <lay-select-option value="DeepSeek-V3" label="DeepSeek-V3"></lay-select-option>
              <lay-select-option value="DeepSeek-R1" label="DeepSeek-R1"></lay-select-option>
            </lay-select>
            </lay-form-item>
          <lay-form-item label="用例作者" prop="account">
            <lay-input v-model="formData.account" allow-clear placeholder="请输入用例作者"></lay-input>
          </lay-form-item>
          <lay-form-item label="上传路径" prop="nodePath">
            <lay-input v-model="formData.nodePath" allow-clear placeholder="请输入用例根目录"></lay-input>
          </lay-form-item>
          <lay-form-item style="text-align: center;">
            <lay-button type="primary" @click="handleSubmit">提交</lay-button>
          </lay-form-item>
          <lay-form-item label="转化进度">
            <div style="height: 20px"></div>
            <lay-progress show-text="转化进度" :percent="progress"></lay-progress>
          </lay-form-item>
        </lay-form>
      </lay-col>
    </lay-row>
  </lay-card>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { uploadAndParseLimitCaseFile,queryProgressApi } from '../../../api/fastApi/AiCase'; // 假设接口文件路径为 @/api/api
import { notify } from '../../../untils/tip'; // 假设通知工具路径为 @/utils/tip

interface FormData {
  file: string | null;
  model: string;
  account: string;
  nodePath: string;
}

// 表单数据
const formData = reactive<FormData>({
  file: null,
  model: '',
  account: '',
  nodePath: ''
});

// 文件对象
const selectedFile = ref<File | null>(null);

// 转化进度
const progress = ref(0);

// 定时器
const timer = ref<number | null>(null);

// 校验规则
const rules = reactive({
  file: [
    { required: true, message: '请选择用例文件', trigger: 'change' }
  ],
   modelType: [
    { required: true, message: '请选择大模型类型', trigger: 'change' }
  ],
  nodePath: [
    { required: true, message: '请输入上传路径', trigger: 'blur' }
  ],
  account: [
    { required: true, message: '请输入用例作者', trigger: 'blur' }
  ]
  // preConditionKey 可选，无需设置 required
});

// 处理文件选择
const handleFileChange = (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    selectedFile.value = target.files[0];
  }
};

// 文件转 Base64
const fileToBase64 = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve((reader.result as string).split(',')[1]); // 去掉 Base64 的前缀
    reader.onerror = error => reject(error);
  });
};

// 查询转化进度
const queryProgress = async (taskId: string) => {
  try {
    const response = await queryProgressApi({ taskId });
    if (response.success) {
      progress.value = Number(response.data);
      console.log('当前进度:', progress.value);
      if (progress.value >= 100) {
        clearInterval(timer.value!);
        notify('success', '用例转换＆上传完成！');
      }
    }
  } catch (error) {
    console.error('查询进度失败:', error);
    notify('failed', '查询进度失败！' + error);
  }
};

// 提交表单的处理函数
const handleSubmit = async () => {
  debugger;
  if (!selectedFile.value || !formData.account || !formData.nodePath ) {
    notify('failed', '参数未设置完整，请检查输入！');
    return;
  }

  try {
    // 将文件转换为 Base64 编码
    const fileBase64 = await fileToBase64(selectedFile.value);

    // 构造 JSON 数据
    const jsonData = {
      file: fileBase64,
      account: formData.account,
      nodePath: formData.nodePath
    };

    // 调用后端接口
    const response = await uploadAndParseLimitCaseFile(jsonData);

    if (response.success) {
      notify('success', '用例转换生成中，请等待...');
      const taskId = response.data; // 获取任务 ID
      progress.value = 0;
      timer.value = setInterval(() => queryProgress(taskId), 3000); // 每 3 秒查询一次进度
    } else {
      notify('failed', '用例转换生成失败！' + response.data);
    }
  } catch (error) {
    console.error('提交失败:', error);
    notify('failed', '用例转换生成失败！' + error);
  }
};
</script>

<style scoped>
.file-input {
  padding: 10px;
  width: 100%;
}
</style>